import "./reset.css";
import { handleTree } from "@/utils/allAppTree";
import { message } from "@/utils/message";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection } from "@pureadmin/utils";
import { type Ref, ref, computed, reactive, onMounted } from "vue";
import { getAppTreeList } from "@/api/serviceMarks";
import { getAccount } from "@/utils/auth";
import { getApiAllList } from "@/api/service";
import { PlusColumn } from "plus-pro-components";
import { logSettingType, serviceType } from "@/utils/commonType";
import { getLogSettings, updateLogSettings } from "@/api/logs";

export function useLogSetting(tableRef: Ref, treeRef: Ref) {
  const dataList = ref([]);
  const loading = ref(true);
  const roleInfo = getAccount().accountType;
  const curTenantId = getAccount().tenantId;

  const settingVisible = ref(false);
  const higherDeptOptions = ref();
  const treeData = ref([]);
  const treeLoading = ref(true);
  const selectedNum = ref(0);
  const settingInfo = reactive<logSettingType>({
    serviceId: "",
    appName: "",
    serviceName: "",
    serviceUrl: "",
    /**
     * 20.业务事件流水号
     */
    bizEventId: "",
    /**
     * 21.业务事件类型
     */
    bizEventType: "",
    /**
     * 21.业务主数据类型
     */
    mdTypeCode: "",
    /**
     * 22.业务主数据ID
     */
    mdId: "",
    setting_desc_summary:
      "业务类型填写说明：取值设置开头指定取值参数来源，来源分五种，分别是请求头（headers）、请求路径（path）、请求体（body）、请求参数（params）、静态取值（static），取值示例如下：",
    setting_desc_1:
      "请求头（headers）取值示例：[headers][user-agent]，user-agent为请求头名称。提取方法与body相同",
    setting_desc_2:
      "请求路径（path）取值示例：[path][3],请求路径（URI，不含域名和端口号部分）按照\"/\"进行分段，分段序号从1开始，获取指定路径段数据",
    setting_desc_3:
      "请求体（body）取值示例：[body][root.user.age],支持请求体为json结构参数，多级json结构以.分隔。例如从JSON数据中提取数据表达式实例：JSON数据###{'store':{'book':[{'title':'Sayings of the Century','price':8.95}]}}###,提取path表达式### $.store.book[0].title ###",
    setting_desc_4:
      "请求参数（params）取值示例：[params][page]，page为请求参数名称",
    setting_desc_5:
      "静态取值（static）取值示例：[static][178****9930],'178****9930'为静态值，不做数据转换"
  });
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: PlusColumn[] = [
    {
      label: "应用名称",
      width: 160,
      prop: "appName",
      valueType: "text"
    },
    {
      label: "服务名称",
      width: 160,
      prop: "serviceName",
      valueType: "text"
    },
    {
      label: "服务地址",
      width: 160,
      prop: "serviceUrl",
      valueType: "text"
    },
    {
      label: "业务",
      width: 160,
      prop: "bizEventType",
      tooltip: "业务事件类型"
    },

    {
      label: "流水号",
      width: 160,
      prop: "bizEventId",
      tooltip: "业务事件流水号"
    },

    {
      label: "对象",
      width: 160,
      prop: "mdTypeCode",
      tooltip: "业务主数据类型"
    },

    {
      label: "对象ID",
      width: 160,
      prop: "mdId",
      tooltip: "业务主数据ID"
    },
    {
      label: "业务",
      width: 160,
      hasLabel: false,
      prop: "setting_desc_summary",
      valueType: "text"
    },
    {
      label: "流水号",
      width: 160,
      hasLabel: false,
      prop: "setting_desc_1",
      valueType: "text"
    },
    {
      label: "业务主数据类型",
      width: 160,
      hasLabel: false,
      prop: "setting_desc_2",
      valueType: "text"
    },
    {
      label: "业务主数据类型",
      width: 160,
      hasLabel: false,
      prop: "setting_desc_3",
      valueType: "text"
    },
    {
      label: "业务主数据类型",
      width: 160,
      hasLabel: false,
      prop: "setting_desc_4",
      valueType: "text"
    },
    {
      label: "业务主数据类型",
      width: 160,
      hasLabel: false,
      prop: "setting_desc_5",
      valueType: "text"
    }
  ];

  const tableColumns: TableColumnList = [
    {
      label: "序号", // 如果需要表格多选，此处label必须设置
      type: "index",
      width: 60
    },
    {
      label: "所属应用",
      prop: "appName",
      width: 180
    },
    {
      label: "服务名称",
      prop: "serviceName",
      width: 180
    },
    {
      label: "服务地址",
      prop: "serviceUrl",
      width: 280
    },
    {
      label: "服务说明",
      prop: "serviceDesc"
    },
    {
      label: "操作",
      fixed: "right",
      width: 120,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });

  function handleUpdate(row) {
    console.log(row);
  }

  function handleDelete(row) {
    message(`您删除了用户编号为${row.id}的这条数据`, { type: "success" });
    onSearch();
  }

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
  }

  async function onSearch(dId?: string, type = "") {
    loading.value = true;
    if (dId === "root") {
      dId = "";
    }
    let params = {};
    if (roleInfo != 1) {
      if (type == "app") {
        params = {
          pagination,
          curTenantId: curTenantId,
          appId: dId
        };
      } else if ((type = "tenant")) {
        params = {
          pagination,
          curTenantId: curTenantId,
          tenantId: dId
        };
      } else {
        params = {
          pagination,
          curTenantId: curTenantId
        };
      }
    } else {
      if (type == "app") {
        params = {
          pagination,
          appId: dId
        };
      } else if ((type = "tenant")) {
        params = {
          pagination,
          tenantId: dId
        };
      } else {
        params = {
          pagination
        };
      }
    }
    getApiAllList(params)
      .then(data => {
        dataList.value = data.data.list;
        pagination.total = data.data.total;
        pagination.pageSize = data.data.pageSize;
        pagination.currentPage = data.data.currentPage;
      })
      .catch(err => {
        message(`加载服务清单异常：${err.message}`, {
          type: "error"
        });
      });
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    treeRef.value.onTreeReset();
    onSearch();
  };

  function onTreeSelect({ pid, selected, nodeType }) {
    onSearch(selected ? pid : "", nodeType);
  }

  function openDialog(row?: serviceType) {
    settingVisible.value = true;
    settingInfo.appName = row.appName;
    settingInfo.serviceId = row.pid;
    settingInfo.serviceName = row.serviceName;
    settingInfo.serviceUrl = row.serviceUri;
    getLogSettings(row.pid)
      .then(result => {
        settingInfo.bizEventId = result.data["bizEventId"];
        settingInfo.bizEventType = result.data["bizEventType"];
        settingInfo.mdTypeCode = result.data["mdTypeCode"];
        settingInfo.mdId = result.data["mdId"];
      })
      .catch(err => {
        message(`读取日志采集配置异常：${err.message}`, {
          type: "error"
        });
      });
  }

  function handleSaveSetting() {
    const data = {
      bizEventType: settingInfo.bizEventType,
      mdId: settingInfo.mdId,
      mdTypeCode: settingInfo.mdTypeCode,
      bizEventId: settingInfo.bizEventId
    };
    updateLogSettings(settingInfo.serviceId, data)
      .then(result => {
        message(`更新日志采集配置成功`, {
          type: "success"
        });
        settingVisible.value = false;
      })
      .catch(err => {
        message(`更新日志采集配置异常：${err.message}`, {
          type: "error"
        });
      });
  }

  onMounted(async () => {
    treeLoading.value = true;
    onSearch();

    // 应用树
    let tenantId = "";
    if (roleInfo != 1) {
      tenantId = curTenantId;
    }
    getAppTreeList(tenantId)
      .then(data => {
        higherDeptOptions.value = handleTree(data.data);
        treeData.value = handleTree(data.data);
      })
      .catch(err => {
        message(`获取应用清单异常：${err.message}`, {
          type: "error"
        });
      });
    treeLoading.value = false;
  });

  return {
    loading,
    tableColumns,
    dataList,
    treeData,
    treeLoading,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    openDialog,
    onTreeSelect,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    settingVisible,
    columns,
    settingInfo,
    handleSaveSetting
  };
}
